package mqtt_thingsboard_connector

import (
	"encoding/json"
	"github.com/panjf2000/ants/v2"
	"go-iot-gateway/internal/channel"
	channel_define "go-iot-gateway/internal/channel/define"
	conf_table_define "go-iot-gateway/internal/conf_table/define"
	"go-iot-gateway/internal/logger"
	"time"
)

func NewThingsBoardMqttClientConnector(channelConfig conf_table_define.ChannelInfo,
	protocolConfInfos []*conf_table_define.ProtocolInfo) (channel_define.ConnectChannel, error) {
	manager := channel.Manager()

	chl := &ThingsBoardMqttClientChannel{}
	chl.channelManager = manager
	chl.protocolInfo = NewThingsBoardMqttProtocolInfo(protocolConfInfos)
	chl.ChannelInfo = channel_define.ChannelInfo{}
	chl.isClosed = false
	chl.ChannelInfo.ChlId = channelConfig.Chl_id
	chl.ChannelInfo.Name = channelConfig.Chl_name
	chl.ChannelInfo.Addr = channelConfig.Chl_addr
	chl.ChannelInfo.Desc = channelConfig.Chl_desc
	chl.ChannelInfo.Protocol = channelConfig.Chl_protocol
	chl.ChannelInfo.SetStatus(channel_define.CONNECT_STATUS_CREATE, "已创建")
	chl.ChannelInfo.ChannelType = channelConfig.Chl_type
	chl.ChannelInfo.ProtocolType = channelConfig.Protocol_type
	chl.ChannelInfo.Frequency = channelConfig.Chl_colt_freq
	chl.ChannelInfo.WaitTime = channelConfig.Chl_wait_time
	connectParams := channel_define.ConnectParams{}
	err := json.Unmarshal([]byte(channelConfig.Chl_main_param), &connectParams)
	if err != nil {
		return nil, err
	}
	chl.ChannelInfo.ConnectParams = connectParams
	channelLogger := logger.NewChannelLogger(channelConfig.Chl_name)
	chl.logger = channelLogger
	chl.rcpChan = make(chan *RPCRequest, MaxRpcChan)
	withFunc, err := ants.NewPool(rpcMaxTaskPool, ants.WithLogger(channelLogger), ants.WithMaxBlockingTasks(0),
		ants.WithNonblocking(true), ants.WithExpiryDuration(10*time.Second), ants.WithPanicHandler(func(i interface{}) {
			channelLogger.Errorf("[panic] rpc 出现 ")
		}))
	if err != nil {
		return nil, err
	}
	chl.rcpTaskPool = withFunc
	return chl, nil
}
